#!/usr/bin/php
<?php
/* This script connects to a schema and outputs a spec file for the loader.
*/

require_once('include/common.php');
require_once('include/mysql.php');

function defgen($item) {
	global $opt;
	if(empty($opt[$item])) {
		switch($item) {
			case 'delimiter':
				$opt[$item]='|';
				break;

			case 'workers':
				$opt[$item]=1;
				break;

			case 'line_terminator':
				$opt[$item]="\\n";
				break;


		}
	}
	if(!empty($opt[$item])) echo "$item=\"" . $opt[$item] . "\"\n";
}

$opt = get_commandline(array('workers==','line_terminator==','delimiter==','enclosure==','skip==','workers==','path==','tables=='));

if(empty($opt['db'])) {
	genspec_help();
	exit;

}

if(in_array('help',array_keys($opt))) {
	genspec_help();
	exit;
}

if(empty($opt['path'])) $opt['path'] = './';

$sql_ = "select TABLE_NAME,GROUP_CONCAT(COLUMN_NAME order by ordinal_position) COLUMNS from information_schema.columns where table_schema='%s' group by 1";

$dbs = explode(',', $opt['db']);

$dal=new MySQLDAL();

if(substr($opt['path'],-1) != '/') $opt['path'] .= '/';

echo "[default]\n";
defgen('delimiter');
defgen('enclosure');
defgen('line_terminator');
defgen('skip');
defgen('workers');
echo "\n";
foreach($dbs as $db) {
	$opt['db'] = $db;
	$dal->my_connect($opt);
	$db = $dal->my_real_escape_string($db);	
	$sql = sprintf($sql_, $db);

	$dal->my_query($sql);
	while($row = $dal->my_fetch_assoc()) {
		echo "[{$row['TABLE_NAME']}]\n";
		echo 'file="' . $opt['path'] . $row['TABLE_NAME'] . ".tbl\"\n";
		echo 'columns=' . $row['COLUMNS'] . "\n\n";
	}

}


